package com.uah;

import java.util.List;

import com.scraper.CourseListingWebData;
import com.scraper.CourseListingWebScraper;
import com.scraper.Link;
import com.scraper.ScraperType;
import com.scraper.WebReader;

import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.widget.TableLayout;

public class CurrentStudentsPage2 extends Activity {
	TableLayout page2TableLayout;
	List<Link> collegeListingsLinks;
	ProgressDialog progDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		BackgroundThread scraperThread = new BackgroundThread();
		scraperThread.start();
		
		if (scraperThread.isAlive())
		{
			progDialog = ProgressDialog.show(this, "Loading",
		            "....please wait....", true);	
		}
		
		super.onCreate(savedInstanceState);
	    setContentView(R.layout.page2);
	    
	    page2TableLayout = (TableLayout) findViewById(R.id.page2TableLayout);
	    page2TableLayout.removeAllViewsInLayout();
	   
	   //pause loop for test
	   try {
		   scraperThread.join();
	    } catch (InterruptedException e) {
	        // ...
	    }
	   
	   // This needs to be done after the scraperThread is done collecting data
	   // Create rows of buttons for each department offering classes in the selected semester
	   int index = 0;
	   int numButtons = 6;
	   Link[] buttonsByRow = new Link[numButtons];
	   for (Link collegeListing : collegeListingsLinks){
		   buttonsByRow[index] = collegeListing;
		   
		   if (index>=5)
		   {
			   DynamicLayoutCreation.createNewRow(buttonsByRow, "page3::", page2TableLayout, page2TableLayout.getContext());
			   index = 0;
		   }
		   else{
			   index++;
		   }
   		}
	}
	
	 public class BackgroundThread extends Thread
	    {
	    	public void run() {  
	    		android.os.Process.setThreadPriority
	    		(android.os.Process.THREAD_PRIORITY_BACKGROUND);
	    		
	    		// Initialize Scraper and Reader (Step 1)
	    		CourseListingWebScraper courseListingScraper = new CourseListingWebScraper();
	    		WebReader webReader = new WebReader(courseListingScraper); 
	    		String courseListingUrl = null;
	    		
	    		//Get course listings department data
	    		Bundle extras = getIntent().getExtras();
	    		if(extras !=null) {
	    			courseListingUrl = extras.getString("URL");
	    			courseListingScraper.setScraperType(ScraperType.CourseListing);
	    			webReader.scrapeWebPage(courseListingUrl);
	    			CourseListingWebData courseListingData = courseListingScraper.getScrapedData(); 
	    			collegeListingsLinks = courseListingData.collegeCourseListings;
	    		}
	        	
	    		if (progDialog.isShowing())
	    			progDialog.dismiss();
	    	}
	    }
	 
	 
}
